/*
 *  Copyright (C), 2015-2023
 *  FileName: cookie_manager
 *  Author: Tonight丶相拥
 *  Date: 7/4/23
 *  Description: 
 **/

// import 'package:dio/dio.dart';

part of httpplugin;

class CookieManager extends Interceptor {
  CookieManager({String? cookie}): this._cookie = cookie;
  String? _cookie;
  String? get cookie => _cookie;
  final String _cookieKey = "Cookie";
  final String _setCookieKey = "set-cookie";

  String get getXhsA1 {
    var result = toMap(_cookie)?.where((element) {
      // print("the elementKey is: ${element.key} === a1 ${element.key.toString().trim() == "a1"}");
      return element is MapEntry<String, String> && element.key.toString().trim() == "a1";
    }).toList() ?? [];
    var a1 = "";
    if (result.length > 0) {
      a1 = (result.last as MapEntry).value.toString();
    }
    return a1;
  }
  // final List<String> _msTokenList = ["msToken", "expires", "domain", "path", "SameSite"];
  // final List<String> _msTokenList = ["msToken", "expires", "domain", "path", "SameSite", "abRequestId"];
  // final List<String> _replaceList = ["secure"];

  void setCookie(String? cookie){
    _cookie = cookie;
  }

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    // TODO: implement onRequest
    assert((){
      print("cookieManager: $_cookie");
      return true;
    }());
    if (_cookie != null && _cookie!.isNotEmpty){
      options.headers.addAll({
        "$_cookieKey": _cookie
      });
    }
    super.onRequest(options, handler);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    // TODO: implement onResponse
    var value = response.headers.value(_setCookieKey);
    // if (value != null && value.isNotEmpty) {
    //   _cookie = "$_cookie$value";
    //   assert((){
    //     print("cookieManager设置Cookie: $_cookie");
    //     return true;
    //   }());
    //   setCookie(_cookie);
    // }
    var valueMap = toMap(value);
    if (valueMap != null && valueMap.isNotEmpty) {
      var result = toMap(_cookie)?.toSet();//?..removeWhere((element) => (element is MapEntry && (_msTokenList.contains((element.key as String).trim())
          //|| (element is String && _replaceList.contains(element)))));
      result!.addAll(valueMap);
      result.removeWhere((element) => element is String && element.isEmpty);
      var resultString = _toString(result.toList());
      assert((){
        print("cookieManager设置Cookie: $resultString");
        return true;
      }());
      setCookie(resultString);
    }
    super.onResponse(response, handler);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    // TODO: implement onError
    super.onError(err, handler);
  }

  String _toString(List lst) {
    String mapString = "";
    lst.forEach((value) {
      if (value is MapEntry) {
        mapString += "${value.key}=${value.value};";
      }else if (value is String){
        mapString += "$value${value.endsWith(";") ? "" : ";"}";
      }
    });
    return mapString;
  }

  Set? toMap(String? value){
    var valueResult = value?.split(';').map((e) {
      var vs = e.split("=");
      if (vs.length >= 2) {
        return MapEntry(vs[0], vs[1]);
      }
      return e;
    }).toSet();
    return valueResult;
  }
}